package klk.shop.objects;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileWriter;
import java.util.Properties;

import klk.shop.utilities.ServletUtilities;

public class BillDocument implements Printable {
	public final String  tl = "\n--------------------------------------------------------------------------\n",
                		 nl = "\n";
    public static Font standardFont = new Font("Courier", Font.BOLD, 12);	
    
    private boolean stamped 		= false,
					cancelled		= false;
	private String 	text 			= "",
					hash			= "";
    public void stamp() { if (!this.stamped)this.stamped = true; }
	public void cancel() { if (!this.cancelled)this.cancelled = this.stamped = true; }
	public void setText(String text) { if (!this.stamped)this.text = text; }
	
    
	public static Font getStandardFont() {
		return standardFont;
	}
	public static void setStandardFont(Font standardFont) {
		BillDocument.standardFont = standardFont;
	}
	public boolean isStamped() {
		return stamped;
	}
	public void setStamped(boolean abgestempelt) {
		this.stamped = abgestempelt;
	}
	public boolean isCancelled() {
		return cancelled;
	}
	public void setCancelled(boolean storniert) {
		this.cancelled = storniert;
	}
	public String getHash() {
		return hash;
	}
	public void setHash(String hash) {
		this.hash = hash;
	}

    public  String getText() 			{ return text; 				}
    	
    @Override
	public String toString() {
        return  getText();
    }

    @Override
	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

        if (pageIndex > 0) 
        {
            return NO_SUCH_PAGE;							
        }
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        graphics.setFont(standardFont);

        String druckText = tl + " " + hash + tl + getText();

        StringBuffer sb = new StringBuffer();
        int index = 0, textLen = druckText.length(), y = 10, tab = 0;
        while (index < textLen) {
            if (druckText.charAt(index) == '\n') {
                graphics.drawString(sb.toString(), 10, y += 14);
                sb = new StringBuffer();
                tab = 0;

            } else if (druckText.charAt(index) == '\t') {
                while (tab++ < 8) {
                    sb.append(' ');
                }
                tab = 0;

            } else {
                sb.append(druckText.charAt(index));
                tab++;

            }
            index++;
            if (tab == 8) {
                tab = 0;
            }
        }
        return PAGE_EXISTS;
    }

    public void print() {

        stamp();

        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper temp = pf.getPaper();
        temp.setImageableArea(0, 0, temp.getWidth(), temp.getHeight());
        pf.setPaper(temp);

        job.setJobName(getHash());
        job.setPrintable(this, pf);

        try {
            job.print();

        } catch (Exception PrintException) {
            PrintException.printStackTrace();
        }
    }

    public void txtDateiSchreiben() {

        try {

            File f = new File( "c:\\bill_"+hash+".txt" );
            FileWriter fw = new FileWriter( f );
            String printText = getText();

            StringBuilder sb = new StringBuilder();
            int index = 0, textLen = printText.length();
            while ( index < textLen ) {
                sb.append( printText.charAt( index++ ) );
            }
            fw.write( sb.toString() );

            fw.close();

        } catch (Exception e) {
        }


    }

    public BillDocument(Properties laLo, Customer customer, Order order) {

        

        StringBuilder paymentMethodText = new StringBuilder(laLo.getProperty("payment", "Payment") + " ");
        if (order.getPaymentMethod() instanceof BankAccount) {
        	paymentMethodText.append(laLo.getProperty("by", "by") + " " + laLo.getProperty("bankAccount", "bank account") + " " + order.getPaymentMethod().toString());
        } else if (order.getPaymentMethod() instanceof CreditCard) {
        	paymentMethodText.append(laLo.getProperty("by", "by") + " " + laLo.getProperty("creditCard", "credit card") + " " + order.getPaymentMethod().toString());
        } else {
        	paymentMethodText.append(laLo.getProperty("on", "on") + " " + laLo.getProperty("delivery", "delivery"));
        }
        
        setText(	laLo.getProperty("bill", "Bill") + "\t\t\t\t\tBremen, " + ServletUtilities.getDateString(laLo, order.getOrderDate()) + nl
                    + nl
                 	+ "KLKSHOP" + nl
                 	+ "Strasse" + nl
                 	+ "Bremen" + nl
                 	+ laLo.getProperty("countryGermany", "Germany") + nl
                 	+ nl
                 	+ nl
                 	+ laLo.getProperty("customerId", "Customer-ID") + ": " + customer.getCustomerId() + nl
                 	+ (customer.getTitle()==0?laLo.getProperty("mrs", "Mrs"):laLo.getProperty("mr", "Mr")) + " " +  customer.getName() + " " + customer.getSurname() + nl
                 	+ customer.getDefaultContactAddress().toString() + nl
                 	+ nl
                 	+ laLo.getProperty("orderId", "Order-ID") + ": " + order.getOrderId() + nl
					+ laLo.getProperty("ipAddress", "IP-Address") + ": " + order.getCustomerIp() + nl
					+ laLo.getProperty("shippingCost", "Shipping cost") + ": " + String.format("%5.2f", order.getShippingCharges()) + nl 
					+ nl
                 	+ order.getShoppingCart().toString() + nl
                 	+ paymentMethodText + nl
                 	+ tl
        );

    }
    // --------------------------------------------------------------------------------------------
}
